import { createInterface } from 'readline'
import { Lexer } from './lexer.js'
import { TokenType } from './token.js'
import { Parser } from './parser.js';
import { evalMonkey, newEnvironment } from './evaluator.js';

const printParserErrors = (outputStream, errors) => {
    errors.forEach((msg) => outputStream.write('\t' + msg + '\n'))
}

export const startRepl = (
    inputStream = process.stdin,
    outputStream = process.stdout
) => {
    const PROMPT = '>> ';
    const rl = createInterface({
        input: inputStream,
        output: outputStream,
        prompt: PROMPT,
    });

    console.log('Hello This is Monkey language')

    const env = newEnvironment();

    rl.prompt()

    rl.on('line', (line) => {
        const lexer = new Lexer(line)
        const parser = new Parser(lexer)
        const program = parser.parseProgram()
        let token = lexer.nextToken()
        if (parser.getErrors().length !== 0) {
            printParserErrors(outputStream, parser.getErrors())
            rl.prompt()
            return
        }

        const evaluated = evalMonkey(program, env);
        if (evaluated) {
            outputStream.write(evaluated.inspect())
            outputStream.write('\n')
        }


        rl.prompt();
    })
    rl.on('close', () => {
        outputStream.write('exting repl!')
    })
}

startRepl();